package com.example.song.mywebviewclient;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;


public class MyWebViewClient extends WebViewClient {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        //  get data fdrom SDcard
        String response = getJsFromSdCard(request);
        WebResourceResponse webResourceResponse = new WebResourceResponse("text/html", "utf-8", new ByteArrayInputStream(response.getBytes()));
        return webResourceResponse;
    }

    @SuppressLint("NewApi")
    private String getJsFromSdCard(final WebResourceRequest request) {
        String jsUrl = "";
        //拦截 URl
        switch (request.getUrl().toString()) {
            case "http://www./":
                jsUrl = "js";
                break;
            default:
                jsUrl = "js";
                break;
        }
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File file = new File(MainActivity.getDir(),
                        jsUrl);
                if (file.exists()) {
                    FileInputStream is = new FileInputStream(file);
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder("");
                    String line = null;
                    //循环读取文件内容
                    while ((line = br.readLine()) != null) {
                        //todo 解密
                        sb.append(line);
                    }
                    br.close();
                    return sb.toString();
                } else {
                    return request.getUrl().toString();
                }

            } else {
                //没有权限
                return request.getUrl().toString();
            }
        } catch (Exception e) {
            //异常
            return request.getUrl().toString();
        }
    }

}
